package com.bbx.taxi.client.Activity.Menu;

import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.text.Html;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.webkit.JavascriptInterface;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.PopupWindow.OnDismissListener;
import android.widget.RelativeLayout;
import butterknife.Bind;

import com.bbx.androidapi.util.ToastUtil;
import com.bbx.api.sdk.Config;
import com.bbx.api.sdk.model.base.BaseRequest;
import com.bbx.api.sdk.model.passanger.MyOrder;
import com.bbx.api.sdk.model.passanger.ShareDetailBuild;
import com.bbx.api.sdk.model.passanger.SharelinkBuild;
import com.bbx.api.sdk.model.passanger.Token;
import com.bbx.api.sdk.model.passanger.Return.ShareDetail;
import com.bbx.api.sdk.model.passanger.Return.ShareStat;
import com.bbx.api.sdk.model.passanger.Return.Sharelink;
import com.bbx.api.sdk.model.passanger.Return.MyOrderList.MyOrders;
import com.bbx.api.sdk.net.base.JsonBuild;
import com.bbx.api.sdk.net.passeger.conn.MyOrderNet;
import com.bbx.api.sdk.net.passeger.conn.ShareDetailNet;
import com.bbx.api.sdk.net.passeger.conn.ShareStatNet;
import com.bbx.api.sdk.net.passeger.conn.SharelinkNet;
import com.bbx.taxi.client.Task.BaseAsyncTask;
import com.bbx.api.util.LogUtils;
import com.bbx.api.util.SharedPreEncryptUtil;
import com.bbx.taxi.client.MyApplication;
import com.bbx.taxi.client.R;
import com.bbx.taxi.client.Activity.Base.BaseBBXActivity;
import com.bbx.taxi.client.Activity.Order.OrderEvaluationActivity2;
import com.bbx.taxi.client.Activity.login.WelcomeActivity;
import com.bbx.taxi.client.Bean.Value;
import com.bbx.taxi.client.Bean.Extra.RecommenMsg;
import com.bbx.taxi.client.Util.AppStarted;
import com.bbx.taxi.client.Util.NetworkDetector;
import com.bbx.taxi.client.widget.Dailog.MyAlertDailog;
import com.bbx.taxi.client.widget.Dailog.MyAlertDailog.onClickSingleListener;
import com.bbx.taxi.client.widget.pop.SharePopView;
import com.bbx.taxi.client.widget.pop.SharePopView.OnShareDetaiFinish;
import com.yanxuwen.loadview.LoadingDialog;
import com.umeng.socialize.bean.RequestType;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.bean.SocializeEntity;
import com.umeng.socialize.bean.StatusCode;
import com.umeng.socialize.controller.UMServiceFactory;
import com.umeng.socialize.controller.UMSocialService;
import com.umeng.socialize.controller.listener.SocializeListeners.SnsPostListener;
import com.umeng.socialize.media.SinaShareContent;
import com.umeng.socialize.media.UMImage;
import com.umeng.socialize.sso.SinaSsoHandler;
import com.umeng.socialize.sso.UMQQSsoHandler;
import com.umeng.socialize.sso.UMSsoHandler;
import com.umeng.socialize.weixin.controller.UMWXHandler;
import com.umeng.socialize.weixin.media.CircleShareContent;
import com.umeng.socialize.weixin.media.WeiXinShareContent;

/**
 * 推荐有奖
 * 
 */
public class RecommenActivity extends BaseBBXActivity implements OnShareDetaiFinish{
//	@Bind(R.id.layout_bg)
//	RelativeLayout layout_bg;
//	@Bind(R.id.btn_share)
//	Button btn_share;
//	@Bind(R.id.pop_background)
//	View pop_background;
//	@Bind(R.id.tv_obtained)
//	TextView tv_obtained;
//	@Bind(R.id.tv_coupon)
//	TextView tv_coupon;
//	@Bind(R.id.tv_prompt)
//	TextView tv_prompt;
	@Bind(R.id.webview)
	WebView webview;
	private ShareStatTask mShareStatTask;
	public String sum="0";
	public String totalsum="0";
	public String totalcnt="0";
	private LoadingDialog dialog;
	/**分享POP*/
	public SharePopView mSharePopView;
	

	protected void onCreate(Bundle savedInstanceState) {
		setContentView(R.layout.activity_recommen);
		super.onCreate(savedInstanceState);
		
	}

	@Override
	protected void initView() {
		if (NetworkDetector.detect(context)){
			MyApplication application =MyApplication.getInstance();
			if(Value.appCity==null||Value.appCity.equals("")){
				onOpenActivity(false,false);
			}else{
				mSharePopView=new SharePopView(context,null);
				mSharePopView.setOnShareDetaiFinish(this);
				mSharePopView.getShareDetai(Value.TYPE_RECOMMEN,0,Value.appCity);
			}
		}else{
			ToastUtil.showToast(context, context.getString(R.string.no_network));
		}
	
		setTitle(true,getString(R.string.recommen_award), -1,getString(R.string.recommen_record));
		
	}


	@Override
	protected void initData() {
	}
	public void loadData(){
		dialog = new LoadingDialog(context,Value.LOADDIALOGTIME);
		if (dialog != null && !dialog.isShowing()) {
			dialog.show();
		}
//		layout_bg.setBackgroundDrawable(new BitmapDrawable(
//				getImageFromAssetsFile("bg_hb.png")));
//		btn_share.setOnClickListener(this);
//		tv_obtained.setOnClickListener(this);
//		tv_obtained.setText(Html.fromHtml("已获得<font color=\"#169bdb\">" + 0
//				+ "</font>元>>"));
		getShareStat();
//		mSharePopView=new SharePopView(context,pop_background);

	        //加上这句话才能使用javascript方法  
	        webview.getSettings().setJavaScriptEnabled(true);
			String access_token;
			String city=Config.CITY;
			try {
				access_token = new String(java.net.URLEncoder.encode(mApplication.getToken(), "UTF-8").getBytes(), "ISO-8859-1");  
			} catch (Exception e) {
				access_token=mApplication.getToken();
			}
			try{city=new String(java.net.URLEncoder.encode(city, "UTF-8").getBytes(), "ISO-8859-1"); }catch(Exception e){}
	        switch(Config.getInstance().Env){
	        case 0:
//				huanjing="环境：开发";
				break;
			case 1://测试
				String ceshiurl="http://weixin.bbxpc.com/wxtest/share"+"?uid="+mApplication.getUid()+"&access_token="+access_token+"&city="+city; 
				LogUtils.e("",ceshiurl+"");
				webview.loadUrl(ceshiurl);
				break;
			case 2://正式
				String zhengshiurl="http://weixin.bbxpc.com/share"+"?uid="+mApplication.getUid()+"&access_token="+access_token+"&city="+city;
				LogUtils.e("",zhengshiurl+"");
				 webview.loadUrl(zhengshiurl);
				break;
	        }
	        //加载assets目录下面的demo.html 界面
//	        webview.loadUrl("file:///android_asset/demo.html");
	       //增加接口方法,让html页面调用  
	        webview.addJavascriptInterface(this,"ncp");  
	        webview.setWebViewClient(new WebViewClient(){
	        	  @Override
                  public void onPageFinished(WebView view, String url) 
                  {
	        		  if (dialog != null ) {
	        				dialog.dismiss();
	        			}
                      super.onPageFinished(view, url);
                  }
	        });
	}
	@Override
	protected void onResume() {
		webview.resumeTimers();
		Token token = SharedPreEncryptUtil.getStringEncryptValue(this,
				SharedPreEncryptUtil.TokenAndUid, "");
		if (token == null || token.equals("")) {
			mApplication.setUid("");
			mApplication.setToken("");
		} else {
			mApplication.setUid(token.uid);
			mApplication.setToken(token.access_token);
		}
		super.onResume();
	}
	@Override
	protected void onPause() {
		webview.pauseTimers();
		super.onPause();
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btn_share:
//			mSharePopView.onShow(v);
			break;
//		case R.id.tv_obtained:
//			startActivity(new Intent(this, RecommenContentActivity.class).putExtra(RecommenMsg.totalsum, totalsum).putExtra(RecommenMsg.totalcnt, totalcnt));
//			break;
		case R.id.tv_right:
			startActivity(new Intent(this, RecommenContentActivity.class).putExtra(RecommenMsg.totalsum, totalsum).putExtra(RecommenMsg.totalcnt, totalcnt));
			break;
		default:
			super.onClick(v);
			break;
		}

	}
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		/** 使用SSO授权必须添加如下代码 */
		UMSsoHandler ssoHandler =mSharePopView.getController().getConfig().getSsoHandler(
				requestCode);
		if (ssoHandler != null) {
			ssoHandler.authorizeCallBack(requestCode, resultCode, data);
		}
	}

//	/**
//	 * 从Assets中读取图片
//	 */
//	private Bitmap getImageFromAssetsFile(String fileName) {
//		Bitmap image = null;
//		AssetManager am = getResources().getAssets();
//		try {
//			InputStream is = am.open(fileName);
//			image = BitmapFactory.decodeStream(is);
//			is.close();
//		} catch (IOException e) {
//			e.printStackTrace();
//		}
//
//		return image;
//
//	}

	/**
	 * 获取获取分享统计信息
	 */
	public void getShareStat() {
		ShareDetailBuild mShareDetailBuild = new ShareDetailBuild(context);
		mShareDetailBuild.uid = mApplication.getUid();
		mShareDetailBuild.access_token = mApplication.getToken();
		mShareDetailBuild.type = Value.TYPE_RECOMMEN;
		mShareStatTask = new ShareStatTask(context, mShareDetailBuild);
		mShareStatTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
	}
	/**
	 * 获取获取分享统计信息
	 */
	private class ShareStatTask extends BaseAsyncTask {

		private ShareDetailBuild mShareDetailBuild;

		public ShareStatTask(Activity context, ShareDetailBuild mShareDetailBuild) {
			super(context,false);
			this.mShareDetailBuild = mShareDetailBuild;
		}

		@Override
		public void onSuccess(int status,Object object) {
			if (object != null) {
				ShareStat mShareStat=(ShareStat)object;
				if(mShareStat!=null){
					totalsum=mShareStat.getTotalsum();
					totalcnt=mShareStat.getTotalcnt();
					totalsum=totalsum!=null?totalsum:"0";
					totalcnt=totalcnt!=null?totalcnt:"0";
//					tv_obtained.setText(Html.fromHtml("已获得<font color=\"#169bdb\">" + totalsum
//							+ "</font>元>>"));
				}

			}else{
				ToastUtil.showToast(context, R.string.no_network);
				finish();
			}
			if (dialog != null) {
				dialog.onDismiss();
			}
		}

		@Override
		public void onFailed(int status, String msg) {
			if (dialog != null) {
				dialog.onDismiss();
			}
			ToastUtil.showToast(context, R.string.no_network);
			finish();
		}

		@Override
		protected Object doInBackground(Object... params) {
			// TODO Auto-generated method stub
			String json = new JsonBuild().setModel(mShareDetailBuild).getJson();
			return new ShareStatNet(context, json);
		}
	}
	protected void onDestroy() {
		if (mShareStatTask != null
				&& mShareStatTask.getStatus() != AsyncTask.Status.FINISHED)
			mShareStatTask.cancel(true);
		super.onDestroy();

	}

	@Override
	public void onShareDetaiFinish(ShareDetail mShareDetail) {
		if (mShareDetail != null) {
			int coupon_switch = mShareDetail.getState();
			if(coupon_switch == ShareDetail.STATUS_OPEN){
				onOpenActivity(true,true);
			}else{
				onOpenActivity(false,true);
			}
		}else{
			onOpenActivity(false,true);
		}
		
	}
	@JavascriptInterface
	public void onShare(final String type,final String url,final int price){
		new AsyncTask<Void, Void, Void>(){

			@Override
			protected Void doInBackground(Void... arg0) {
				// TODO Auto-generated method stub
				return null;
			}

			@Override
			protected void onPostExecute(Void result) {
				LogUtils.e("xxx",type+","+url+","+price);
				mSharePopView.sum=price+"";
			   if(type.equals("weixin")){
				   mSharePopView.performShare(SHARE_MEDIA.WEIXIN, url);
			   }else if(type.equals("friend")){
				   mSharePopView. performShare(SHARE_MEDIA.WEIXIN_CIRCLE,  url);
			   }
			   else if(type.equals("xinlang")){
				   mSharePopView. performShare(SHARE_MEDIA.SINA,url);
			   }
				super.onPostExecute(result);
			}
		  	
		}.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
	}

	MyAlertDailog mydialog;
	public void onOpenActivity(boolean isopen,boolean isLocation){
		if(mydialog==null){
			mydialog= new MyAlertDailog(this);
		}
		if(isopen){
			loadData();
			webview.setVisibility(View.VISIBLE);
		}else{
			mydialog.setTitle(getString(R.string.mydailog_title));
			mydialog.setContent(isLocation?"抱歉，您所在的城市不支持当前活动！":"哎呀，定位失败了！请检查网络或定位设置哦");
			mydialog.setSingle("好");
			if (mydialog != null && !mydialog.isShowing()) {
				mydialog.show();
			}
			mydialog.setOnClickSingleListener(new onClickSingleListener() {
				
				@Override
				public void onClickSingle() {
					finish();
				}
			});
		}
	}
}
